﻿using System.IO;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MG.Repository;
using MG.SmartHMI.Common;
using MG.SmartHMI.Entity.DAO;
using MG.SmartHMI.Model.Common.Enum;
using MG.SmartHMI.Model.VO;
using MG.Util.Data;
using MG.Util.Log;
using Microsoft.Win32;
using MiniExcelLibs;
using MiniExcelLibs.Attributes;
using MiniExcelLibs.OpenXml;
using Nelibur.ObjectMapper;

namespace MG.SmartHMI.ViewModel.Pages.Setting
{
    public partial class MessageStateViewModel : ObservableRecipient
    {
        [ObservableProperty]
        private List<MessageStateConfigVO> dataList;

        [ObservableProperty]
        private string monitoringAddress;

        [ObservableProperty]
        private int defaultCode = 0;

        [ObservableProperty]
        private List<string> messageLevelSource = Enum.GetNames<EnumMessageLevel>().ToList();

        public MessageStateViewModel()
        {
            Update2UI();
        }

        [RelayCommand]
        private void AddSingle()
        {
            RepositoryService<MessageStateConfig>.Instance.Add(new MessageStateConfig());
            Update2UI();
        }

        [RelayCommand]
        private void SaveAll()
        {
            Task.Run(() =>
            {
                DataList.ForEach(data => RepositoryService<MessageStateConfig>.Instance.Update(TinyMapper.Map<MessageStateConfig>(data)));
                RepositoryService<Config>.Instance.UpdateFiled(t => new Config() { Key = "MonitoringAddress", Value = MonitoringAddress },
                  x => x.Key.Equals("MonitoringAddress"));
                Update2UI();
                EventBus.Default.PopUpSuccess("保存成功");
                EventBus.Default.Log(new LogInfo($"保存 状态监测配置"));
                EventBus.Default.Log(new LogInfo($"保存 状态监测配置\r\n{DataList.ToJson()}", LogLevel.Trace));
            });
        }

        [RelayCommand]
        private void Save(MessageStateConfigVO voinf)
        {
            Task.Run(() =>
            {
                RepositoryService<MessageStateConfig>.Instance.Update(TinyMapper.Map<MessageStateConfig>(voinf));

                Update2UI();
                EventBus.Default.PopUpSuccess("保存成功");
                EventBus.Default.Log(new LogInfo($"状态监测配置 [{voinf.Name}]"));
                EventBus.Default.Log(new LogInfo($"状态监测配置 [{voinf.Name}]  \r\n{TinyMapper.Map<MessageStateConfig>(voinf).ToJson()}", LogLevel.Trace));
            });
        }

        [RelayCommand]
        private void Delete(MessageStateConfigVO voinfo)
        {
            var res = MessageBox.Show($"是否删除{voinfo.Name} 信息", "提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Information);
            if (res != System.Windows.MessageBoxResult.Yes) return;

            RepositoryService<MessageStateConfig>.Instance.Update(TinyMapper.Map<MessageStateConfig>(voinfo));

            Update2UI();
            EventBus.Default.Log(new LogInfo($"删除状态监测配置 [{voinfo.Name}]"));
            EventBus.Default.Log(new LogInfo($"删除状态监测配置 [{voinfo.Name}] \r\n {voinfo.ToJson()} ", LogLevel.Trace));
        }

        [RelayCommand]
        private void ImportData()
        {
            var res = MessageBox.Show("是否导入新配置", null, System.Windows.MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (res != MessageBoxResult.Yes) { return; }
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.RestoreDirectory = false;
            openFileDialog.Title = "选择导入表格";
            openFileDialog.Filter = "表格 | *.xlsx";//Jpeg  "
            if (openFileDialog.ShowDialog() == true)
            {
                var fileName = openFileDialog.FileName;
                var mesageres = MessageBox.Show("新数据将覆盖现有数据，请确认是否导入？", null, MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (mesageres == MessageBoxResult.No) return;

                Task.Run(() =>
                {
                    //先删除现在的数据再导入
                    foreach (var item in DataList)
                    {
                        RepositoryService<MessageStateConfig>.Instance.UpdateFiled(t => new MessageStateConfig() { IsDelete = true }, x => x.Id.Equals(item.Id));
                    }

                    DataList?.Clear();
                    if (!File.Exists(fileName))
                    {
                        DataList = new();
                        return;
                    }
                    var datalist = MiniExcel.Query<MessageStateConfig>(fileName).ToList();
                    RepositoryService<MessageStateConfig>.Instance.Add(datalist);

                    Update2UI();
                    EventBus.Default.Log(new LogInfo($"导入表格[{fileName}]"));
                });
            }
        }

        [RelayCommand]
        private void ExportData()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "表格(*.xlsx)|*.xlsx";
            saveFileDialog.CheckFileExists = false;
            saveFileDialog.AddExtension = true;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName = $"状态监测配置{DateTime.Now:yyyy-MM-dd HH-mm-ss}";

            if (saveFileDialog.ShowDialog() == true)
            {
                if (File.Exists(saveFileDialog.FileName)) File.Delete(saveFileDialog.FileName);
                var config = new OpenXmlConfiguration
                {
                    DynamicColumns = new DynamicExcelColumn[] {
                    new DynamicExcelColumn("Id"){Ignore=true},
                    new DynamicExcelColumn("CreateTime"){Ignore=true},
                    new DynamicExcelColumn("UpdateTime"){Ignore=true},
                    new DynamicExcelColumn("Remarks"){Ignore=true},
                new DynamicExcelColumn("IsDelete"){Ignore=true},
                }
                };
                var savedata = DataList.Select(t => TinyMapper.Map<MessageStateConfig>(t)).ToList();
                MiniExcel.SaveAs(saveFileDialog.FileName, savedata, configuration: config);
                EventBus.Default.Log(new LogInfo($"导出表格[{saveFileDialog.FileName}]"));
            }
        }

        private void Update2UI()
        {
            var listaxis = RepositoryService<MessageStateConfig>.Instance.Query(t => !t.IsDelete);
            DataList = listaxis.Select(x => TinyMapper.Map<MessageStateConfigVO>(x)).OrderBy(t2 => t2.Id).ToList();

            MonitoringAddress = RepositoryService<Config>.Instance.Query(t => t.Key.Equals("MonitoringAddress")).First().Value;
        }
    }
}